<template>
  <div class="map-container">
    <div class="mapCheckedBox">
      <el-checkbox v-model="areaChecked" class="white-text-checkbox"
        >显示情报区域范围</el-checkbox
      >
    </div>
    <div ref="chartRef" class="chart-container"></div>

    <div class="mapTabs">
      <div
        class="tab"
        @click="handleDetail('0')"
        :class="{ tabCur: currTabIndex == '0' }"
      >
        机场预测详情
      </div>
      <div
        class="tab tabs"
        @click="handleDetail('1')"
        :class="{ tabCur: currTabIndex == '1' }"
      >
        机场终端区预测详情
      </div>
      <div
        @click="handleDetail('2')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '2' }"
      >
        区域统计预测详情
      </div>
      <div
        @click="handleDetail('3')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '3' }"
      >
        航路态势预测详情
      </div>
      <div
        @click="handleDetail('4')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '4' }"
      >
        航路分时预测详情
      </div>
      <div
        @click="handleDetail('5')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '5' }"
      >
        航线分时预测详情
      </div>
    </div>
    <DetailAir
      v-if="currTabIndex == '0'"
      :airTestsObj="airTestsObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '1'"
      :airTestsObj="airTests1Obj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailArea
      v-if="currTabIndex == '2'"
      :airTestsAreaObj="airTestsAreaObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailRoute
      v-if="currTabIndex == '3'"
      :airTestsRouteObj="airTestsRouteObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailFilter
      v-if="currTabIndex == '4' || currTabIndex == '5'"
      :airTestsFilterObj="airTestsFilterObj"
      @update-curr-detail-index="handleTabChange"
    />
    <NoDatas
      v-if="currTabIndex == '6'"
      @update-curr-detail-index="handleTabChange"
    />
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  computed,
  defineProps,
} from "vue";
import * as echarts from "echarts/core";
import { GeoComponent, TooltipComponent } from "echarts/components";
import { MapChart, LinesChart, ScatterChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import isValidValue from "@/utils/tools/isValidValue";
import DetailAir from "./detailAir.vue";
import DetailArea from "./detailArea.vue";
import DetailRoute from "./detailRoute.vue";
import DetailFilter from "./detailFilter.vue";
import NoDatas from "./noDatas.vue";

// 注册所需模块
echarts.use([
  GeoComponent,
  MapChart,
  ScatterChart,
  LinesChart,
  CanvasRenderer,
  TooltipComponent,
]);

// 接收父组件传递的机场数据
const props = defineProps({
  airports: {
    type: Array,
    default: () => [],
  },
  airports1: {
    type: Array,
    default: () => [],
  },
  airports2: {
    type: Array,
    default: () => [],
  },
  areaStatic: {
    type: Array,
    default: () => [],
  },

  airTestsObj: {
    type: Object,
    default: () => ({}),
  },
  airTests1Obj: {
    type: Object,
    default: () => ({}),
  },
  airTestsAreaObj: {
    type: Array,
    default: () => [],
  },
  airTestsRouteObj: {
    type: Array,
    default: () => [],
  },
  airTestsFilterObj: {
    type: Array,
    default: () => [],
  },
});

const currTabIndex = ref("");

// 组件状态
const areaChecked = ref(false);
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
const lineWidth = computed(() => 1);
const gridLines = ref([]);
const gridSize = ref(2.5);
const visibleRange = ref({
  minLon: 0,
  maxLon: 0,
  minLat: 0,
  maxLat: 0,
});
const isFirstLoad = ref(true);

const handleTabChange = (newTabIndex) => {
  currTabIndex.value = newTabIndex;
};

// 地图常量配置
const MAP_CONFIG = {
  backgroundColor: "transparent",
};

// 异步加载地图数据
const loadMapData = async () => {
  try {
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

const handleDetail = (index) => {
  console.log(index, "this is index");
  console.log(isValidValue(props.airTestsObj), "this is index");
  if (index == 0 && isValidValue(props.airTestsObj)) {
    console.log(111);
    currTabIndex.value = index;
  } else if (index == 1 && isValidValue(props.airTests1Obj)) {
    console.log(111);
    currTabIndex.value = index;
  } else {
    currTabIndex.value = "6";
  }

  // if (index == 0 && xx) {
  //   currTabIndex.value = index;
  // } else if (index == 1 && xx) {
  //   console.log("1");
  // } else if (index == 2 && xx) {
  //   console.log("1");
  // } else if (index == 3 && xx) {
  //   console.log("1");
  // } else if (index == 4) {
  //   if (XX 有 XX) { } else {
  //     console.log("统一的一个报错页面");
  //   }
  // } else if (index == 5) {
  //    if (XX 有 XX) { } else {
  //     console.log("统一的一个报错页面");
  //   }
  // } else {
  //   console.log("统一的一个报错页面");
  // }
};

// 绘制网格 - 只在首次加载时执行
const drawGrid = () => {
  if (!isReady.value || !isFirstLoad.value) return;

  gridLines.value = generateGridData();
  const option = chart.value.getOption();
  const nonGridSeries = option.series.filter(
    (series) => series.type === "map" || series.type === "scatter"
  );

  chart.value.setOption({
    series: [...nonGridSeries, ...gridLines.value],
  });
};

// 生成网格线数据 - 确保经纬度为 2.5° 整数倍
const generateGridData = () => {
  const lines = [];
  const { minLon, maxLon, minLat, maxLat } = visibleRange.value;
  const step = gridSize.value; // 固定 2.5° 间隔

  // -------------------------- 绘制纬线（固定纬度，如 30°、32.5°、35°） --------------------------
  // 计算 >= minLat 的第一个 2.5° 整数倍（向上取整对齐）
  const startLat = Math.ceil(minLat / step) * step;
  // 计算 <= maxLat 的最后一个 2.5° 整数倍（向下取整对齐）
  const endLat = Math.floor(maxLat / step) * step;

  // 按 2.5° 间隔迭代生成纬线
  for (let lat = startLat; lat <= endLat; lat += step) {
    const fixedLat = Number(lat.toFixed(1)); // 保留1位小数，避免浮点数误差（如 32.5000001）
    lines.push({
      tip: "绘制网格线",
      type: "lines",
      zlevel: 3,
      name: `纬线_${fixedLat}`,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
      },
      emphasis: {
        disabled: false,
      },
      data: [
        [
          [minLon, fixedLat],
          [maxLon, fixedLat],
        ],
      ],
    });
  }

  // -------------------------- 绘制经线（固定经度，如 100°、102.5°、105°） --------------------------
  // 计算 >= minLon 的第一个 2.5° 整数倍
  const startLon = Math.ceil(minLon / step) * step;
  // 计算 <= maxLon 的最后一个 2.5° 整数倍
  const endLon = Math.floor(maxLon / step) * step;

  // 按 2.5° 间隔迭代生成经线
  for (let lon = startLon; lon <= endLon; lon += step) {
    const fixedLon = Number(lon.toFixed(1));
    lines.push({
      type: "lines",
      name: `经线_${fixedLon}`, // 核心：将精确经度存入 name，供 tooltip 读取
      zlevel: 3,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
      },
      emphasis: {
        disabled: false, // 必须开启，否则无法触发 tooltip
      },
      data: [
        [
          [fixedLon, minLat],
          [fixedLon, maxLat],
        ],
      ],
    });
  }

  return lines;
};

// 初始化图表 - 只在首次加载时执行
const initChart = () => {
  if (!isReady.value || !chart.value || !isFirstLoad.value) return;

  const option = {
    backgroundColor: MAP_CONFIG.backgroundColor,
    tooltip: {
      show: true,
      trigger: "item",
      formatter: (params) => {
        // ------------- 核心修改：从 series.name 提取 2.5° 整数倍的经纬度 -------------
        if (params.seriesType === "lines") {
          const name = params.seriesName;
          // 匹配纬线（格式：纬线_32.5）
          if (name.startsWith("纬线_")) {
            const lat = name.split("_")[1];
            return `纬线: ${lat}°N`; // 显示如 "纬线: 32.5°N"
          }
          // 匹配经线（格式：经线_102.5）
          else if (name.startsWith("经线_")) {
            const lon = name.split("_")[1];
            return `经线: ${lon}°E`; // 显示如 "经线: 102.5°E"
          }
          return "网格线信息";
        }

        // ------------- 保留原有其他系列的逻辑（不修改）-------------
        if (!params.value || !Array.isArray(params.value)) {
          return "经纬度信息";
        }
        const lon = Number(params.value[0]);
        const lat = Number(params.value[1]);
        if (isNaN(lon) || isNaN(lat)) {
          return "经纬度信息";
        }
        return `经度: ${lon.toFixed(4)}°<br>纬度: ${lat.toFixed(4)}°`;
      },
    },
    geo: {
      map: "china",
      // aspectScale: 0.75,
      // layoutCenter: [450, 337.5], //["50%", "52%"],
      // layoutSize: "90%",
      center: [104, 31], // 中国几何中心经纬度（可自定义）
      zoom: 1.2, // 缩放级别（1 为默认，越大地图越近）
      roam: false,
      emphasis: {
        disabled: true,
      },
      itemStyle: {
        normal: {
          borderColor: "#4896a4",
          borderWidth: 0.5,
          color: {
            type: "linear-gradient",
            x: 0,
            y: 1500,
            x2: 2500,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#132c5f" },
              { offset: 1, color: "#132c5f" },
            ],
            global: true,
          },
          opacity: 0.5,
        },
        emphasis: {
          areaColor: "rgba(0, 157, 161, 0.5)",
          borderColor: "rgba(147, 235, 248, 1)",
        },
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
          emphasis: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
        },
      ],
      z: 1,
    },
    series: [
      {
        type: "map",
        map: "china",
        tooltip: { show: false },
        label: {
          show: false,
          // color: "#FFFFFF",
          // fontSize: 12,
          // emphasis: {
          //   color: "#FFFFFF",
          //   fontWeight: "normal",
          // },
        },
        // aspectScale: 0.75,
        // layoutCenter: [450, 335], //["50%", "50.5%"],
        center: [104, 30], // 中国几何中心经纬度（可自定义）
        zoom: 1.2, // 缩放级别（1 为默认，越大地图越近）
        // layoutSize: "90%",
        roam: false,
        emphasis: {
          disabled: true,
        },
        itemStyle: {
          normal: {
            borderColor: "rgba(147, 235, 248, 0.6)",
            borderWidth: 0.8,
            areaColor: {
              type: "linear-gradient",
              x: 0,
              y: 1200,
              x2: 1000,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#132c5f" },
                { offset: 1, color: "#132c5f" },
              ],
              global: true,
            },
          },
          emphasis: {
            areaColor: "rgba(0, 157, 161, 0.5)",
            borderColor: "rgba(147, 235, 248, 0.6)",
          },
        },
        zlevel: 0,
      },
    ],
  };

  chart.value.setOption(option);

  nextTick(async () => {
    await new Promise((resolve) => setTimeout(resolve, 100));

    const container = chartRef.value;
    const { width: containerWidth, height: containerHeight } =
      container.getBoundingClientRect();

    const topLeft = chart.value.convertFromPixel("geo", [0, 0]);
    const topRight = chart.value.convertFromPixel("geo", [containerWidth, 0]);
    const bottomLeft = chart.value.convertFromPixel("geo", [
      0,
      containerHeight,
    ]);
    const bottomRight = chart.value.convertFromPixel("geo", [
      containerWidth,
      containerHeight,
    ]);

    const actualMinLon = Math.min(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMaxLon = Math.max(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMinLat = Math.min(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );
    const actualMaxLat = Math.max(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );

    visibleRange.value = {
      minLon: actualMinLon,
      maxLon: actualMaxLon,
      minLat: actualMinLat,
      maxLat: actualMaxLat,
    };

    drawGrid();
    // 首次加载时绘制机场
    updateAirports();
    // 标记为非首次加载
    isFirstLoad.value = false;

    // 绑定双击事件（核心新增）
    bindAirportDoubleClick();
  });
};

// 绑定大飞机双击事件（核心新增）
const bindAirportDoubleClick = () => {
  if (!chart.value) return;

  chart.value.on("dblclick", (params) => {
    // 仅处理飞机系列的双击事件
    if (params.seriesName === "airports" && params.data?.isBigPlane) {
      console.log("双击了大飞机，信息如下：", {
        机场名称: params.data.name,
        经度: params.data.longitude,
        纬度: params.data.latitude,
        原始数据: params.data,
      });
    }
    // 2. 新增：停车场双击逻辑
    if (params.seriesName === "parkingLots") {
      console.log("双击了停车场，信息如下：", {
        停车场名称: params.data.name || "未知",
        经度: params.data.longitude?.toFixed(4) || "未知",
        纬度: params.data.latitude?.toFixed(4) || "未知",
        容量: params.data.capacity || "未知",
        原始数据: params.data,
      });
    }
    // 3. 新增：静态区域矩形双击逻辑
    if (params.seriesName === "areaStaticRect") {
      // 从 params.data 中获取完整对象，经纬度等字段在 area 嵌套对象中
      const pointData = params.data;
      console.log("双击了静态区域矩形，信息如下：", {
        静态区域ID: pointData.pointId, // 顶层对象直接有 pointId，无需改
        经纬度: `${pointData.area.longitude.toFixed(
          4
        )}, ${pointData.area.latitude.toFixed(4)}`, // 新增 .area
        海拔: pointData.area.elevation.toFixed(2), // 新增 .area
        时间范围: `${pointData.startTime} ~ ${pointData.endTime}`, // 顶层对象，无需改
        原始数据: pointData,
      });
    }
  });
};

// 更新机场数据
const updateAirports = () => {
  const greenPlane = new URL(
    "../../../assets/images/raim/airlvicon.png",
    import.meta.url
  ).href;
  const bigPlane = new URL(
    "../../../assets/images/raim/airlanbigicon.png",
    import.meta.url
  ).href;
  const planeLot = new URL(
    "../../../assets/images/raim/planelot.png",
    import.meta.url
  ).href;

  if (!isReady.value || !chart.value) return;

  const airports1NameSet = new Set(
    props.airports1.map((item) => item.name?.trim())
  );
  const airportData = props.airports.map((airport) => ({
    name: airport.name,
    value: [airport.longitude, airport.latitude],
    isBigPlane: airports1NameSet.has(airport.name?.trim()),
    ...airport,
  }));

  const smallPlaneData = airportData.filter((item) => !item.isBigPlane);
  const bigPlaneData = airportData.filter((item) => item.isBigPlane);
  const finalAirportData = [...smallPlaneData, ...bigPlaneData];

  const option = chart.value.getOption();
  const oldAirportSeriesIndex = option.series.findIndex(
    (s) => s.name === "airports"
  );
  if (oldAirportSeriesIndex !== -1) {
    option.series.splice(oldAirportSeriesIndex, 1);
  }

  option.series.push({
    type: "scatter",
    name: "airports",
    coordinateSystem: "geo",
    zlevel: 4,
    tooltip: {
      show: true,
      trigger: "item",
      padding: 12,
      backgroundColor: "rgba(0, 15, 40, 0.9)",
      borderColor: "rgba(147, 235, 248, 0.8)",
      borderWidth: 1,
      textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
      formatter: (params) => {
        if (params.data?.isBigPlane) {
          return `
            <div>
              <p><b>机场名称：</b>${params.data.name || "未知"}</p>
              <p><b>经度：</b>${params.data.longitude?.toFixed(4) || "未知"}</p>
              <p><b>纬度：</b>${params.data.latitude?.toFixed(4) || "未知"}</p>
            </div>
          `;
        }
        return "";
      },
    },
    data: finalAirportData.map((item) => {
      return {
        ...item,
        symbol: `image://${item.isBigPlane ? bigPlane : greenPlane}`,
        symbolSize: item.isBigPlane ? [36, 60] : [18, 30],
        zlevel: item.isBigPlane ? 10 : 5,
      };
    }),
  });
  if (isValidValue(props.airports2)) {
    const oldParkingIndex = option.series.findIndex(
      (s) => s.name === "parkingLots"
    );
    if (oldParkingIndex !== -1) {
      option.series.splice(oldParkingIndex, 1);
    }

    option.series.push({
      type: "scatter",
      name: "parkingLots",
      coordinateSystem: "geo",
      zlevel: 6, // 层级高于小飞机，低于大飞机（可根据需求调整）
      tooltip: {
        show: true,
        trigger: "item",
        padding: 12,
        backgroundColor: "rgba(0, 15, 40, 0.9)",
        borderColor: "rgba(147, 235, 248, 0.8)",
        borderWidth: 1,
        textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
        formatter: (params) => {
          return `
          <div>
            <p><b>停车场名称：</b>${params.data.name || "未知"}</p>
            <p><b>经度：</b>${params.data.longitude?.toFixed(4) || "未知"}</p>
            <p><b>纬度：</b>${params.data.latitude?.toFixed(4) || "未知"}</p>
            ${
              params.data.capacity
                ? `<p><b>容量：</b>${params.data.capacity} 个</p>`
                : ""
            }
          </div>
        `;
        },
      },
      data: props.airports2.map((parking) => ({
        ...parking,
        // 使用停车场自定义图标
        symbol: `image://${planeLot}`,
        // 图标大小（根据实际图标调整）
        symbolSize: [24, 40],
        zlevel: 6,
      })),
    });
  }

  if (isValidValue(props.areaStatic) && props.areaStatic.length > 0) {
    console.log(1);
    const oldAreaStaticIndex = option.series.findIndex(
      (s) => s.name === "areaStaticRect"
    );
    if (oldAreaStaticIndex !== -1) {
      option.series.splice(oldAreaStaticIndex, 1);
    }
    console.log(2);

    // ---------------- 1. 核心配置：网格单元固定参数（2.5°×2.5°） ----------------
    const gridStep = gridSize.value; // 固定2.5°，与网格线间隔一致
    // 网格单元的边界必须是 gridStep 的整数倍（如 30=2.5×12，32.5=2.5×13）

    // ---------------- 2. 计算每个矩形的尺寸（核心修复：绑定网格单元边界） ----------------
    const rectSeriesData = props.areaStatic.map((item) => {
      const { longitude: centerLon, latitude: centerLat } = item.area;
      console.log(3);

      try {
        console.log(4);
        if (!chart.value || !chart.value.getModel().getComponent("geo")) {
          throw new Error("地图组件未初始化");
        }
        console.log(5);

        // ---------------- 核心步骤1：找到中心点所属的网格单元边界 ----------------
        // 计算网格单元的左边界（经度最小值，gridStep的整数倍）
        const gridLonLeft = Math.floor(centerLon / gridStep) * gridStep;
        // 计算网格单元的右边界（经度最大值 = 左边界 + 2.5°）
        const gridLonRight = gridLonLeft + gridStep;
        // 计算网格单元的下边界（纬度最小值，gridStep的整数倍）
        const gridLatBottom = Math.floor(centerLat / gridStep) * gridStep;
        // 计算网格单元的上边界（纬度最大值 = 下边界 + 2.5°）
        const gridLatTop = gridLatBottom + gridStep;

        // 打印验证：确认边界是2.5°的整数倍（如 30、32.5、35）
        console.log(`网格单元边界：`, {
          经度范围: `${gridLonLeft}°~${gridLonRight}°E`,
          纬度范围: `${gridLatBottom}°~${gridLatTop}°N`,
        });

        // ---------------- 核心步骤2：基于网格边界转换像素坐标 ----------------
        // 左上角像素坐标（网格左边界+上边界）
        const pixelTopLeft = chart.value.convertToPixel("geo", [
          gridLonLeft,
          gridLatTop,
        ]);
        // 右下角像素坐标（网格右边界+下边界）
        const pixelBottomRight = chart.value.convertToPixel("geo", [
          gridLonRight,
          gridLatBottom,
        ]);
        console.log(pixelTopLeft, "pixelTopLeft（网格左上角）");
        console.log(pixelBottomRight, "pixelBottomRight（网格右下角）");

        if (
          !pixelTopLeft ||
          !pixelBottomRight ||
          isNaN(pixelTopLeft[0]) ||
          isNaN(pixelBottomRight[1])
        ) {
          throw new Error("坐标转换结果无效");
        }

        // ---------------- 核心步骤3：计算矩形像素尺寸（覆盖整个网格） ----------------
        const rectWidth = Math.max(
          1,
          Math.abs(pixelBottomRight[0] - pixelTopLeft[0])
        );
        const rectHeight = Math.max(
          1,
          Math.abs(pixelBottomRight[1] - pixelTopLeft[1])
        );

        // ---------------- 核心步骤4：矩形中心点设为网格单元的几何中心 ----------------
        const gridCenterLon = (gridLonLeft + gridLonRight) / 2; // 网格中心经度
        const gridCenterLat = (gridLatBottom + gridLatTop) / 2; // 网格中心纬度

        console.log(rectWidth, "rectWidth（网格宽度）");
        return {
          name: `静态区域${item.pointId}`,
          value: [gridCenterLon, gridCenterLat, rectWidth, rectHeight], // 中心点=网格中心
          ...item,
          rectWidth,
          rectHeight,
          // 附加网格信息，方便tooltip显示
          gridInfo: {
            lonRange: `${gridLonLeft.toFixed(1)}°~${gridLonRight.toFixed(1)}°E`,
            latRange: `${gridLatBottom.toFixed(1)}°~${gridLatTop.toFixed(1)}°N`,
          },
        };
      } catch (error) {
        console.log(8);
        console.warn(
          `静态区域${item.pointId}尺寸计算失败，使用默认值:`,
          error.message
        );
        return {
          name: `静态区域${item.pointId}`,
          value: [centerLon, centerLat, 50, 50],
          ...item,
          rectWidth: 50,
          rectHeight: 50,
          gridInfo: { lonRange: "未知", latRange: "未知" },
        };
      }
    });
    console.log(9);

    // ---------------- 3. 矩形系列配置（保持不变，仅优化tooltip显示） ----------------
    option.series.push({
      type: "scatter",
      name: "areaStaticRect",
      coordinateSystem: "geo",
      zlevel: 7,
      symbol: "rect",
      symbolSize: (data) => {
        console.log("矩形尺寸:", [data[2], data[3]]);
        return [data[2] || 50, data[3] || 50];
      },
      itemStyle: {
        color: "rgba(255, 0, 0, 0.8)",
        borderColor: "#ffffff",
        borderWidth: 2,
      },
      tooltip: {
        show: true,
        trigger: "item",
        formatter: (params) => {
          const point = params.data;
          return `
        <div>
          <p><b>区域ID：</b>${point.pointId}</p>
          <p><b>网格单元：</b>${point.gridInfo.lonRange} / ${
            point.gridInfo.latRange
          }</p>
          <p><b>中心点：</b>${point.value[0].toFixed(
            1
          )}°, ${point.value[1].toFixed(1)}°</p>
        </div>
      `;
        },
      },
      data: rectSeriesData,
    });
  }
  chart.value.setOption(option);
};

// 监听数据变化
watch(
  () => [props.airports, props.airports1, props.airports2, props.areaStatic],
  () => {
    console.log(props.areaStatic, "静态区域");
    updateAirports();
  },
  { deep: true }
);

// 组件生命周期
onMounted(() => {
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas",
        useDirtyRect: true,
      });
      const dataLoaded = await loadMapData();
      if (!dataLoaded) {
        return;
      }
      isReady.value = true;
      initChart();
    });
  }, 100);
});

// 窗口大小监听
watch(
  () => chartRef.value?.clientWidth,
  (newWidth) => {
    if (newWidth && isReady.value) {
      chart.value.resize({ animation: { duration: 300 } });
    }
  }
);

// 组件销毁
onUnmounted(() => {
  console.log("组件销毁");
  if (chart.value) {
    // 移除事件监听（避免内存泄漏）
    chart.value.off("dblclick");
    chart.value.dispose();
    chart.value = null;
  }
  isReady.value = false;
});
</script>

<style scoped>
.mapCheckedBox {
  position: absolute;
  left: 20px;
  z-index: 1;
  top: 17px;
  .white-text-checkbox :deep(.el-checkbox__label) {
    color: #ffffff !important;
    font-size: 14px;
  }
}
.mapTabs {
  position: absolute;
  left: 130px;
  bottom: -54px;
  .tab {
    cursor: pointer;
    float: left;
    margin-right: 8px;
    color: #c5d6e6;
    font-size: 14px;
    text-align: center;
    width: 100px;
    height: 44px;
    line-height: 44px;
    background-image: url("../../../assets/images/raim/tabUnChange.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
  .tabs {
    padding: 0 15px;
    line-height: 22px;
  }
  .tabs1 {
    padding: 0 20px;
    line-height: 22px;
  }
  .tabCur {
    color: #fff;
    background-image: url("../../../assets/images/raim/tabChange.png");
  }
}

.map-container {
  position: relative;
  width: 900px;
  float: left;
  height: 675px;
  margin-top: 30px;
  margin-left: 30px;
}
.chart-container {
  width: 900px;
  height: 675px;
  background: transparent;
}
</style>
